package com.itheima.stock.sharding;


import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;
import java.util.Optional;
import java.util.stream.Collectors;

public class CommonAlg4Db implements PreciseShardingAlgorithm<Date>, RangeShardingAlgorithm<Date> {
    @Override
    public String doSharding(Collection<String> dbNames, PreciseShardingValue<Date> preciseShardingValue) {
        String columnName = preciseShardingValue.getColumnName();
        String logicTableName = preciseShardingValue.getLogicTableName();
        Date date = preciseShardingValue.getValue();
        int Year = new DateTime(date).getYear();

        Optional<String> result = dbNames.stream().filter(dbName -> dbName.endsWith(String.valueOf(Year))).findFirst();

        if(result.isPresent()){
            return result.get();
        }
        return null;
    }

    @Override
    public Collection<String> doSharding(Collection<String> dbNames, RangeShardingValue<Date> rangeShardingValue) {
        String columnName = rangeShardingValue.getColumnName();
        String logicTableName = rangeShardingValue.getLogicTableName();
        Range<Date> range = rangeShardingValue.getValueRange();
        if(range.hasLowerBound()){
            Date startTime = range.lowerEndpoint();
            int startYear = new DateTime(startTime).getYear();
            dbNames = dbNames.stream().filter(dbName -> Integer.parseInt(dbName.substring(dbName.lastIndexOf("-")+1))>=startYear).collect(Collectors.toList());
        }
        if(range.hasUpperBound()){
            Date endTime = range.upperEndpoint();
            int endYear = new DateTime(endTime).getYear();
            dbNames = dbNames.stream().filter(dbName -> Integer.parseInt(dbName.substring(dbName.lastIndexOf("-")+1))<=endYear).collect(Collectors.toList());
        }

        return dbNames;
    }
}
